package com.smyx.case1;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DistributeClient {

    private static final String CONNECTION_STRING = "vm110:2181,vm111:2181,vm112:2181";
    private static final int SESSION_TIME = 2000;
    private static final String PARENT_NODE = "/servers";
    private ZooKeeper zkClient = null;

    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(CONNECTION_STRING, SESSION_TIME, event -> {
            // 再次启动监听
            try {
                getServerList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void getServerList() throws InterruptedException, KeeperException {
        // 1 获取服务器子节点信息，并且对父节点进行监听
        List<String> children = zkClient.getChildren(PARENT_NODE, true);
        // 2 存储服务器信息列表
        ArrayList<String> servers = new ArrayList<>();
        // 3 遍历所有节点，获取节点中的主机名称信息
        for (String child : children) {
            byte[] data = zkClient.getData(PARENT_NODE + "/" + child, false, null);
            servers.add(new String(data));
        }
        // 4 打印服务器列表信息
        log.info("打印服务器列表信息>>>> {}", servers);
    }

    private void business() throws InterruptedException {
        log.info("client is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        DistributeClient client = new DistributeClient();
        //1.获取zk连接
        client.getConnect();
        //2.获取servers 的子节点信息，从中获取服务器信息列表
        client.getServerList();
        //3.业务进程启动
        client.business();
    }
}
